package com.sca.schedule.consumer;

import com.rabbitmq.client.Channel;
import com.sca.schedule.config.RabbitConfig;
import com.sca.schedule.service.TimerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

/**
 * @author liuxianfei
 * @since 2020/11/20 13:42
 */
@Slf4j
@Component
public class ScheduleConsumer {

    private final TimerService timerService;

    public ScheduleConsumer(TimerService timerService) {
        this.timerService = timerService;
    }

    /**
     * 定时消息消费
     *
     * @param dataMap
     * @param channel
     * @param headers
     */
    @RabbitListener(
        bindings = @QueueBinding(
            value = @Queue(value = RabbitConfig.QUEUE_POLL, durable = "true"),
            exchange = @Exchange(value = RabbitConfig.EXCHG_SCHEDULE, type = "topic"),
            key = RabbitConfig.RTKEY_WAIT_POLL
        )
    )
    @RabbitHandler
    public void pollConsumer(@Payload Map<String, Serializable> dataMap, Channel channel, @Headers Map<String, Object> headers) {
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(tag, false);
            timerService.createTimer(dataMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
